package com.zzyl.nursing.service.impl;

import java.util.*;

import com.zzyl.common.core.domain.model.LoginUser;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.common.utils.StringUtils;
import com.zzyl.framework.web.service.TokenService;
import com.zzyl.nursing.dto.UserLoginRequestDto;
import com.zzyl.nursing.service.WeChatService;
import com.zzyl.nursing.vo.UserLoginVo;
import lombok.Builder;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.mapper.FamilyMemberMapper;
import com.zzyl.nursing.domain.FamilyMember;
import com.zzyl.nursing.service.IFamilyMemberService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

/**
 * 老人家属Service业务层处理
 * 
 * @author zsn
 * @date 2025-05-23
 */
@Service
public class FamilyMemberServiceImpl extends ServiceImpl<FamilyMemberMapper, FamilyMember> implements IFamilyMemberService
{
    @Autowired
    private FamilyMemberMapper familyMemberMapper;

    /**
     * 查询老人家属
     * 
     * @param id 老人家属主键
     * @return 老人家属
     */
    @Override
    public FamilyMember selectFamilyMemberById(Long id)
    {
        return getById(id);
    }

    /**
     * 查询老人家属列表
     * 
     * @param familyMember 老人家属
     * @return 老人家属
     */
    @Override
    public List<FamilyMember> selectFamilyMemberList(FamilyMember familyMember)
    {
        return familyMemberMapper.selectFamilyMemberList(familyMember);
    }

    /**
     * 新增老人家属
     * 
     * @param familyMember 老人家属
     * @return 结果
     */
    @Override
    public int insertFamilyMember(FamilyMember familyMember)
    {
        return save(familyMember) ? 1 : 0;
    }

    /**
     * 修改老人家属
     * 
     * @param familyMember 老人家属
     * @return 结果
     */
    @Override
    public int updateFamilyMember(FamilyMember familyMember)
    {
        return updateById(familyMember) ? 1 : 0;
    }

    /**
     * 批量删除老人家属
     * 
     * @param ids 需要删除的老人家属主键
     * @return 结果
     */
    @Override
    public int deleteFamilyMemberByIds(Long[] ids)
    {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 删除老人家属信息
     * 
     * @param id 老人家属主键
     * @return 结果
     */
    @Override
    public int deleteFamilyMemberById(Long id)
    {
        return removeById(id) ? 1 : 0;
    }


    @Autowired
    private WeChatService weChatService;
    @Autowired
    private TokenService tokenService;

    private static List<String> NICK_NAME_List = Arrays.asList(
            "一一得一","一二得二","二二得四","三三得九"
    );
    /**
     * 小程序微信登录
     *
     * @param dto
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public UserLoginVo login(UserLoginRequestDto dto) {
        //1.获取openId
        String openId = weChatService.getOpenId(dto.getCode());
        if(StringUtils.isBlank(openId)){
            throw new BaseException("获取openId为空");
        }
        //2.判断是否有用户,没有创建
        FamilyMember familyMember = this.lambdaQuery().eq(FamilyMember::getOpenId, openId).one();
        if(familyMember==null){
            //打乱集合
            Collections.shuffle(NICK_NAME_List);
            //随机生成昵称
            String nickName = NICK_NAME_List.get(0) + RandomStringUtils.randomNumeric(5);
            //创建用户
            familyMember = FamilyMember.builder().openId(openId).name(nickName).build();

            boolean result = this.save(familyMember);
            if (!result){
                throw new BaseException("创建用户失败");
            }
        }
        //3.判断是否有手机号
        String phone = familyMember.getPhone();
        if(StringUtils.isBlank(phone)){
            //4.没有使用openId获取
            String phoneNumber = weChatService.getPhone(dto.getPhoneCode());
            if(StringUtils.isBlank(phoneNumber)){
                throw new BaseException("通过临时凭证获取电话号码失败");
            }
            familyMember.setPhone(phoneNumber);
        }
        //5.获取令牌
        HashMap<String, Object> userMap = new HashMap<>();
        userMap.put("userId",familyMember.getId());
        userMap.put("name",familyMember.getName());
        String token = tokenService.createToken(userMap);
        //6.返回数据
        return UserLoginVo.builder().nickName(familyMember.getName()).token(token).build();
    }
}
